import { Buy } from '../models';

export default function (router) {
  /**
   * 获取用户消费记录
   */
  router.get('/api/front/buy/records', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const total = await Buy.countDocuments({ userid });
    const buys = await Buy.find({ userid }, 'goodid amount chapter create_time')
      .populate({
        path: 'goodid',
        select: 'bookid',
        populate: {
          path: 'bookid',
          select: 'img_url name'
        }
      })
      .sort({ create_time: -1 })
      .skip((page - 1) * limit)
      .limit(limit);
    const result = buys.map(item => {
      let tmp = {};
      tmp.img_url = item.goodid.bookid.img_url;
      tmp.amount = item.amount;
      tmp.book_name = item.goodid.bookid.name;
      tmp.chapter_num = item.chapter;
      tmp.create_time = item.create_time;
      return tmp;
    });
    await ctx.json(true, 'success', { total, list: result });
  });
}
